using MediatR;
using Microsoft.EntityFrameworkCore;
using RBAC.Domain.SmartHealthcare.Hosiptial;
using RBAC.ErrorCode;
using RBAC.Interstructrue;
using RBAC.Interstructrue.Base;
using SmartHealthcare.Write.Api.Application.Command.InpatientRegistry;

namespace SmartHealthcare.Write.Api.Application.Handler.InpatientRegistry
{
    /// <summary>
    /// 更新病人预交金额处理器
    /// </summary>
    public class UpdateAdvancePaymentHandler : IRequestHandler<UpdateAdvancePaymentCommand, APIResult<int>>
    {
        private readonly RBACDbContext _dbContext;
        private readonly IBaseRepository<InpatientRegistryModel> _inpatientRegistryRepository;
        private readonly ILogger<UpdateAdvancePaymentHandler> _logger;

        public UpdateAdvancePaymentHandler(
            RBACDbContext dbContext,
            IBaseRepository<InpatientRegistryModel> inpatientRegistryRepository,
            ILogger<UpdateAdvancePaymentHandler> logger)
        {
            _dbContext = dbContext;
            _inpatientRegistryRepository = inpatientRegistryRepository;
            _logger = logger;
        }

        /// <summary>
        /// 更新病人预交金额（在原有金额基础上累加）
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<APIResult<int>> Handle(UpdateAdvancePaymentCommand request, CancellationToken cancellationToken)
        {
            var result = new APIResult<int>();

            try
            {
                // 验证参数
                if (!request.IsValid())
                {
                    result.Code = APIEnums.Fail;
                    result.Msg = "参数验证失败，请检查病人卡号、姓名和预交金额";
                    return result;
                }

                _logger.LogInformation($"开始更新病人预交金额，病人卡号：{request.MedicalCard}，病人姓名：{request.PatientName}，增加金额：{request.AddAdvancePayment}");

                // 查找病人的住院登记记录
                var inpatientRegistry = await _dbContext.inpatientRegistries
                    .FirstOrDefaultAsync(x => x.MedicalCard == request.MedicalCard 
                        && x.IsDeleted == false, cancellationToken);

                if (inpatientRegistry == null)
                {
                    result.Code = APIEnums.Fail;
                    result.Msg = "未找到该病人的住院登记记录";
                    _logger.LogWarning($"未找到病人卡号为{request.MedicalCard}的住院登记记录");
                    return result;
                }

                // 验证病人姓名是否匹配
                var patient = await _dbContext.patientLists
                    .FirstOrDefaultAsync(x => x.MedicalCard == request.MedicalCard 
                        && x.Name == request.PatientName 
                        && x.IsDeleted == false, cancellationToken);

                if (patient == null)
                {
                    result.Code = APIEnums.Fail;
                    result.Msg = "病人卡号与姓名不匹配，请检查输入信息";
                    _logger.LogWarning($"病人卡号{request.MedicalCard}与姓名{request.PatientName}不匹配");
                    return result;
                }

                // 记录原金额
                var oldAmount = inpatientRegistry.AdvancePayment;
                
                // 计算新金额（在原有金额基础上累加）
                var newAmount = oldAmount + request.AddAdvancePayment;

                // 更新预交金额
                inpatientRegistry.AdvancePayment = newAmount;

                // 保存更改
                var updateResult = _inpatientRegistryRepository.Update(inpatientRegistry);

                if (updateResult > 0)
                {
                    result.Data = updateResult;
                    result.Code = APIEnums.Success;
                    result.Msg = $"更新成功，原金额：{oldAmount}，增加金额：{request.AddAdvancePayment}，新金额：{newAmount}";
                    
                    _logger.LogInformation($"成功更新病人{request.PatientName}(卡号：{request.MedicalCard})的预交金额，从{oldAmount}增加到{newAmount}，增加金额：{request.AddAdvancePayment}");
                }
                else
                {
                    result.Code = APIEnums.Fail;
                    result.Msg = "更新失败，请稍后重试";
                    _logger.LogError($"更新病人{request.PatientName}(卡号：{request.MedicalCard})的预交金额失败");
                }
            }
            catch (Exception ex)
            {
                result.Code = APIEnums.Fail;
                result.Msg = "更新病人预交金额时发生异常";
                _logger.LogError(ex, $"更新病人预交金额时发生异常，病人卡号：{request.MedicalCard}，病人姓名：{request.PatientName}");
            }

            return result;
        }
    }
} 